package demo1;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mirac
 * Date: 2025-09-22
 * Time: 17:45
 */
//自己第一次的想法
public class Solution {
    public String longestCommonPrefix(String[] strs) {
        //处理边界
        if (strs == null || strs.length == 0) {
            return "";
        }
        if (strs.length == 1){
            return strs[0];
        }
        String s1 = strs[0];
        String s2 = strs[1];
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < (s1.length() > s2.length()?
                s2.length():s1.length()); i++) {
            char ch1 = s1.charAt(i);
            char ch2 = s2.charAt(i);
            if (ch1 == ch2) {
                stringBuilder.append(ch1);
            }else {
                break;
            }
        }

        //第一个字符串和第二个字符串公共的前缀部分
        String publicPart = stringBuilder.toString();

        //从第3个字符串开始遍历
        for (int i = 2; i < strs.length; i++) {
            String str = strs[i];
            StringBuilder s = new StringBuilder();
            for (int j = 0; j < (str.length() > publicPart.length()?
                    publicPart.length():str.length()); j++) {
                char ch1 = publicPart.charAt(j);
                char ch2 = str.charAt(j);
                if (ch1 == ch2) {
                    s.append(ch1);
                }else {
                    break;
                }
            }
            publicPart = s.toString();
        }

        return publicPart;
    }
}
